package com.mp.chart.charts;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.app.CommonType;
import com.android.model.info.LocalSp;
import com.mp.chart.components.AJXAxis;
import com.mp.chart.components.MarkerView;
import com.mp.chart.components.XAxis;
import com.mp.chart.components.YAxis;
import com.mp.chart.data.AJData;
import com.mp.chart.data.BarLineScatterCandleDataSet;
import com.mp.chart.data.CandleData;
import com.mp.chart.data.CandleDataSet;
import com.mp.chart.data.CandleEntry;
import com.mp.chart.data.Entry;
import com.mp.chart.data.KLineData;
import com.mp.chart.data.LineData;
import com.mp.chart.data.LineDataSet;
import com.mp.chart.formatter.ValueFormatter;
import com.mp.chart.formatter.XValueFormatter;
import com.mp.chart.listener.AJChartTouchListener;
import com.mp.chart.listener.OnChartGestureListener;
import com.mp.chart.listener.OnChartValueSelectedListener;
import com.mp.chart.listener.OnMarketSelectValueListener;
import com.mp.chart.listener.OnScrollDataListener;
import com.mp.chart.markerview.HightCircleMarkerView;
import com.mp.chart.markerview.LoadingMarkerView;
import com.mp.chart.markerview.ValueMarkerView;
import com.mp.chart.utils.Highlight;
import com.mp.chart.utils.HqKlineDb;
import com.mp.chart.utils.IndexModel;
import com.mp.chart.utils.Utils;
import com.mp.chart.utils.ViewPortHandler;
import com.mp.chart.view.MaterialProgressDrawable;
import com.android.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * k线图
 * 柱状图
 */
public class KLineCombinedChart extends LinearLayout implements OnScrollDataListener, OnChartValueSelectedListener, AJChartTouchListener.OnLoadingViewListener {
    private KLineChart mKLineChart;
    private AJXAxis mKLineChartXAxis;
    private KLineChart mAffilateChart;
    private int ma5Color;
    private int ma10Color;
    private int ma30Color;
    private int ma60Color;
    private int highlightColor;
    private int decreasingColor;
    private Paint.Style decreasingPaintStyle;
    private int increasingColor;
    private Paint.Style increasingPaintStyle;
    private int pointColor;
    private AJChartTouchListener.OnLoadingViewListener mOnLoadingviewListener;
    private OnMarketSelectValueListener mOnMarketSelectValueListener;
    private float maxRang;
    private float minRang;
    private float pointSize;
    private YAxis.YAxisLabelPosition mYAxisLablePostion;
    private MaterialProgressDrawable progress;
    //    private ImageView waitingView;
    private float mYLabelOffset;
    private float leftOffset;
    private float rightOffset;
    private OnRefreshAffilcateChart mOnRefreshAffilcateChart;
    private boolean mIsHiddenYLabels;
    private int mXLabelPosition;
    private int gridLineColor;
    private int yAxixLabelColor;
    private TextView tvKlineIndex, tvVolumeIndex;
    private int topClickNum = 0;
    private HqKlineDb hqKlineDb;
    private boolean isFullScreen = false;
    private View volumeIndex;

    int isMoveToLastType = 0;
    private TextView maxVolumeTextView;
    private List<String> xVals;
    private ArrayList<CandleEntry> yVals;
    private ArrayList<Entry> minList;
    private ArrayList<Entry> ma5List;
    private ArrayList<Entry> ma10List;
    private ArrayList<Entry> ma30List;
    private int kLinaCount;
    private CandleData candleData;
    private CandleDataSet candleDataSet;
    private ArrayList<LineDataSet> lineDataSets;
    private LineDataSet lineDataSetMin;
    private LineDataSet lineDataSetMa5;
    private LineDataSet lineDataSetMa10;
    private LineDataSet lineDataSetMa30;
    private LineData lineDate;

    public interface TopOnClickListener {
        void OnClick(int p, TextView textView);
    }

    public void setTopOnClickListener(TopOnClickListener onClickListener) {
        this.topOnClickListener = onClickListener;
    }

    private TopOnClickListener topOnClickListener;


    public KLineCombinedChart(Context context) {
        super(context);
        init(context);
    }

    public KLineCombinedChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public KLineCombinedChart(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.ma5Color = 0xff9038F4;
        this.ma10Color = 0xffBDC4E3;
        this.ma30Color = 0xffFFFF00;
        this.ma60Color = 0xffE43395;
        this.highlightColor = 0xff12A4FF;
        this.decreasingColor = LocalSp.getInstance(context).getBeginColor();//跌
        this.increasingColor = LocalSp.getInstance(context).getEndColor();//涨
        this.decreasingPaintStyle = Paint.Style.FILL;
        this.increasingPaintStyle = Paint.Style.FILL;
        this.pointColor = Color.rgb(255, 102, 0);
        this.pointSize = 4f;
        setOrientation(VERTICAL);
        mKLineChart = new KLineChart(context, "kline");
        mAffilateChart = new KLineChart(context, "klinebottom");
//        addView(mKLineChart, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 3));
        addKLineChart(context);
        //柱状图
        addAfficalteChart(context);
        hqKlineDb = new HqKlineDb(context);
        //联动
        mAffilateChart.setOnSyncChartListener(mKLineChart);
        mKLineChart.setOnSyncChartListener(mAffilateChart);

        initChartConfig();

        // setLeftRightOffset(Utils.convertDpToPixel(10), Utils.convertDpToPixel(10));
        // setDragOffsetX(Utils.convertDpToPixel(50));


    }

    /**
     * 设置图表缩放的系数
     *
     * @param chart       K线或者成交量控件
     * @param xVolume     X轴的刻度集合
     * @param getDataType 获取data的次数
     */
    public void setPostScale(KLineCombinedChart chart, ArrayList<String> xVolume, int getDataType) {
        final ViewPortHandler viewPortHandlerCombined = chart.getViewPortHandler();
        viewPortHandlerCombined.setMaximumScaleX(setMaxScale(xVolume.size(), getDataType));
        Matrix matrixCombined = viewPortHandlerCombined.getMatrixTouch();
        final float xScaleCombined = 3;
        matrixCombined.postScale(xScaleCombined, 1f);

    }

    /**
     * 控制一屏显示的数据的个数
     *
     * @param count       总数据size
     * @param getDataType 获取data的次数
     */
    public float setMaxScale(float count, int getDataType) {
        float max = 1;
        if (getDataType == 0) {
            max = count / 90;
        } else {
            max = count / 90;
        }
        return max;
    }


    /*加入K图*/
    private void addKLineChart(Context context) {
        FrameLayout frameLayout = new FrameLayout(context);
       /* waitingView = new ImageView(context);
        progress = new MaterialProgressDrawable(context, waitingView);
        progress.setColorSchemeColors(Color.rgb(88, 168, 208));
        progress.setAlpha(255);
        waitingView.setImageDrawable(progress);*/
     /*   TextView tvIndex=new TextView(context);
        tvIndex.setText("MACD(5,10,20)");*/
        View kLineIndex = LayoutInflater.from(getContext()).inflate(R.layout.view_chart_index, null);
        tvKlineIndex = (TextView) kLineIndex.findViewById(R.id.tvChartIndex);
        tvKlineIndex.setVisibility(GONE);
        frameLayout.addView(mKLineChart, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        FrameLayout.LayoutParams ivLayout = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ivLayout.gravity = Gravity.RIGHT;

        frameLayout.addView(kLineIndex, ivLayout);
        addView(frameLayout, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 3));
        //closeAffilateWaiting();
        tvKlineIndex.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                topOnClickListener.OnClick(++topClickNum, tvKlineIndex);
            }
        });
    }

    /*加入柱状图*/
    private void addAfficalteChart(Context context) {
        FrameLayout frameLayout = new FrameLayout(context);
       /* waitingView = new ImageView(context);
        progress = new MaterialProgressDrawable(context, waitingView);
        progress.setColorSchemeColors(Color.rgb(88, 168, 208));
        progress.setAlpha(255);
        waitingView.setImageDrawable(progress);*/
     /*   TextView tvIndex=new TextView(context);
        tvIndex.setText("MACD(5,10,20)");*/

        // 竖屏选择指标的view
//        afficalteIndex = LayoutInflater.from(getContext()).inflate(R.layout.view_chart_bottomindex, null);
//        afficalteIndex.setVisibility(GONE);
//        tvAffilcateIndex = (TextView) afficalteIndex.findViewById(R.id.tvChartIndex);
//        ivChartMiddleSet = (ImageView) afficalteIndex.findViewById(R.id.ivChartMiddleSet);

//        volumeIndex = LayoutInflater.from(getContext()).inflate(R.layout.view_chart_volume,null);
//        tvVolumeIndex = (TextView) volumeIndex.findViewById(R.id.tvChartVolume);
//
//        frameLayout.addView(mAffilateChart, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//        FrameLayout.LayoutParams ivLayout = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
////        frameLayout.addView(volumeIndex, ivLayout);
//        ivLayout.gravity = Gravity.LEFT;
//        ivLayout.gravity = Gravity.TOP;
//        ivLayout.topMargin = 40;
//
////        mAffilateChart.addView(tvVolumeIndex,ivLayout);
//
//
//        addView(addView2());

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        RelativeLayout relativeLayout = new RelativeLayout(getContext());
        relativeLayout.setLayoutParams(layoutParams);

        ViewGroup.LayoutParams vlp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        ViewGroup.LayoutParams vlp2 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        maxVolumeTextView = new TextView(getContext());

        maxVolumeTextView.setTextSize(10);

        maxVolumeTextView.setTextColor(getResources().getColor(R.color.main_text));

        mAffilateChart.setLayoutParams(vlp);

        maxVolumeTextView.setLayoutParams(vlp2);

        relativeLayout.addView(mAffilateChart);

        relativeLayout.addView(maxVolumeTextView);

        addView(relativeLayout, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 1));

        //closeAffilateWaiting();

//        tvAffilcateIndex.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IndexIntroActivity.startActivity(getContext());
//            }
//        });
//        ivChartMiddleSet.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IndexSetActivity.startActivity(getContext());
//            }
//        });


//        frameLayout.addView(mAffilateChart, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//        frameLayout.addView(volumeIndex);
//        addView(frameLayout, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 2));
    }


   /* public void showAffilateWaiting() {
        progress.start();
        waitingView.setVisibility(View.VISIBLE);
    }

    public void closeAffilateWaiting() {
        progress.stop();
        waitingView.setVisibility(View.INVISIBLE);
    }*/


   /* public void setWaitingColor(int... colors) {
        progress.setColorSchemeColors(colors);
    }
*/

    public void setExtraTopOffset(float offset) {
        mKLineChart.setExtraTopOffset(offset);
    }

    private void initChartConfig() {

        mKLineChart.setDescription("");
        mKLineChart.setNoDataText("");
        /*设置范围内，y轴大小放缩*/
        mKLineChart.setAutoScaleMinMaxEnabled(true);

        mKLineChart.setDrawBorders(true);
        mKLineChart.setBorderWidth(1f);
        mKLineChart.setDoubleTapToZoomEnabled(false);
        mKLineChart.setBorderColor(Color.argb(255, 31, 35, 50));
        mKLineChart.setDescription("");
        mKLineChart.setDragEnabled(true);
        mKLineChart.setDragDecelerationFrictionCoef(0.9f);
//            combinedChart.animateXY(300, 300);
//        mKLineChart.setHighlightPerDragEnabled(false);

        // scaling can now only be done on x- and y-axis separately
        mKLineChart.setPinchZoom(false);
        mKLineChart.setScaleYEnabled(false);
        mKLineChart.setScaleXEnabled(false);
        mKLineChart.setDrawGridBackground(false);
        mKLineChart.setDrawBorders(false);
        mKLineChart.setHighlightStyle(true);//高亮
//        mKLineChart.setBorderColor(gridLineColor);

        mKLineChartXAxis = mKLineChart.getXAxis();
        mKLineChartXAxis.setLabelsToSkip(20);

        mKLineChartXAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        mKLineChartXAxis.setDrawGridLines(true);
        //mKLineChartXAxis.drawGridDashedLine(mKLineChart.DEFAULT_DASH_EFFECT);
        mKLineChartXAxis.setDrawAxisLine(false);

        YAxis leftAxis = mKLineChart.getAxisLeft();
        leftAxis.setLabelCount(5);
        leftAxis.setYlabelStatic(true);
        leftAxis.setDrawLabels(true);
        leftAxis.setDrawGridLines(true);
        // leftAxis.drawGridDashedLine(mKLineChart.DEFAULT_DASH_EFFECT);
        leftAxis.setDrawAxisLine(false);
        leftAxis.setStartAtZero(false);

        YAxis rightAxis = mKLineChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setEnabled(false);
        rightAxis.setStartAtZero(false);

        mKLineChart.getLegend().setEnabled(false);
        mKLineChart.setDragDecelerationEnabled(true);

        mKLineChart.setOnLoadingViewListener(this);
        mKLineChart.setOnScrollDataListener(this);
        mKLineChart.setOnChartValueSelectedListener(this);

        setXAxisLabelPosition(AJXAxis.XAXISPOSITION_MIDDLE);

    }

    //全屏下右上角指标不可点击
    public void setIsFullScreen(boolean isFullScreen) {
        this.isFullScreen = isFullScreen;
        if (isFullScreen) {
            tvKlineIndex.setClickable(false);
//            tvAffilcateIndex.setClickable(false);
          /*  String strTop=tvKlineIndex.getText().toString();
            String strBottom=tvAffilcateIndex.getText().toString();
            tvKlineIndex.setText(strTop.substring(0,strTop.length()-2));
            tvAffilcateIndex.setText(strBottom.substring(0,strBottom.length()-2));*/
        }
    }

    public void setTouchEnable(boolean enable) {
        mKLineChart.setTouchEnabled(enable);
        mAffilateChart.setTouchEnabled(enable);
    }

    public void setDragOffsetX(float offsetX) {
        mKLineChart.setDragOffsetX(offsetX);
        mAffilateChart.setDragOffsetX(offsetX);

    }

    public void setLeftRightOffset(float left, float right) {

//        mKLineChart.setExtraLeftOffset(left);
//        mKLineChart.setExtraRightOffset(right);
//
//        mAffilateChart.setExtraRightOffset(right);
//        mAffilateChart.setExtraLeftOffset(left);
//
        this.leftOffset = left;
        this.rightOffset = right;
    }

    public void setXAxisValueFormat(XValueFormatter format) {
        mKLineChartXAxis.setValueFormatter(format);
        mAffilateChart.getXAxis().setValueFormatter(format);
    }

    public void setLoadingMarkerView(LoadingMarkerView loadingMarkerView) {
        mKLineChart.setLoadingMarkerView(loadingMarkerView);
    }

    public void setHighLowValueMarkerView(MarkerView highValueMarkerView, MarkerView lowValueMarkerView) {
        mKLineChart.setHighValueMarkerView(highValueMarkerView);
        mKLineChart.setLowValueMarkerView(lowValueMarkerView);

    }

    public void setMarkerViewVisibility(boolean visibility) {
        mKLineChart.setHighValueMarkerViewVisibility(visibility);
    }

    public void setMaxVolumeMarkerView(MarkerView maxVolumeMarkerView) {
        mKLineChart.setMaxVolumeMarkerView(maxVolumeMarkerView);

    }

    public void setDrawBorder(int borderColor, float borderWidth) {


        mKLineChart.setDrawBorders(true);
        mKLineChart.setBorderWidth(borderWidth);
        mKLineChart.setBorderColor(borderColor);

        mAffilateChart.setDrawBorders(true);
        mAffilateChart.setBorderWidth(borderWidth);
        mAffilateChart.setBorderColor(borderColor);

    }

    /*柱状图塞数据*/
    public void setAffilateChartData(AJData AJData) {

        if (AJData == null) {
            mAffilateChart.setVisibility(View.GONE);
            return;
        }
        if (mAffilateChart.getData() == AJData) {
            return;
        }
        setFirstDataSetHighlight(AJData);
        mAffilateChart.setVisibility(View.VISIBLE);
        mAffilateChart.setData(AJData);

        if (this.minRang != 0 && this.maxRang != 0) {
            mAffilateChart.setVisibleXRange(this.minRang, this.maxRang);
        }
//        mAffilateChart.moveViewToX(AJData.getXValCount());
        mAffilateChart.invalidate();

    }

    private void setFirstDataSetHighlight(AJData AJData) {

        int count = AJData.getDataSetCount();

        for (int i = 0; i < count; i++) {

            final BarLineScatterCandleDataSet<?> dataSetByIndex = AJData.getDataSetByIndex(i);
            dataSetByIndex.setHighlightEnabled(i == 0);
            if (i == 0) {
                dataSetByIndex.setHighLightColor(this.highlightColor);
            }
            dataSetByIndex.setDrawValues(false);

        }


    }


    public void restoreAffilateChart() {
        mAffilateChart.restoreSetting();
        initAffilateChartConfig();
    }

    /*初始化柱状图*/
    private void initAffilateChartConfig() {
        mAffilateChart.setDescription("");
        mAffilateChart.setNoDataText("");
        //mAffilateChart.getAxisLeft().setXOffset(mYLabelOffset);
        // mAffilateChart.getAxisLeft().setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        mAffilateChart.setScaleYEnabled(false);
        mAffilateChart.setScaleXEnabled(true);
        mAffilateChart.setAutoScaleMinMaxEnabled(true);
        mAffilateChart.setHighlightStyle(true);//highlight颜色默认style为白色
        mAffilateChart.setDrawGridBackground(false);
        AJXAxis mBarChartXAxis = mAffilateChart.getXAxis();
        mBarChartXAxis.setDrawGridLines(true);
        //
        mBarChartXAxis.setPosition(XAxis.XAxisPosition.TOP);
        mAffilateChart.getLegend().setEnabled(false);
        mAffilateChart.getAxisRight().setEnabled(false);
        mAffilateChart.getAxisLeft().setDrawGridLines(true);
        mAffilateChart.getAxisLeft().setGridColor(this.gridLineColor);
        mAffilateChart.getAxisLeft().setAxisLineColor(this.gridLineColor);
        mAffilateChart.getAxisLeft().setTextColor(this.yAxixLabelColor);
        //mAffilateChart.getAxisLeft().drawGridDashedLine(mKLineChart.DEFAULT_DASH_EFFECT);
        mAffilateChart.getXAxis().setGridColor(this.gridLineColor);
        mAffilateChart.getXAxis().setLabelsToSkip(20);
        mAffilateChart.getXAxis().setAxisLineColor(this.gridLineColor);
        //mAffilateChart.getXAxis().drawGridDashedLine(mKLineChart.DEFAULT_DASH_EFFECT);
//        mAffilateChart.getAxisLeft().setLabelCount(6);
        mAffilateChart.getAxisLeft().setStartAtZero(false);
        mAffilateChart.getAxisLeft().setDrawLabels(mIsHiddenYLabels);
        mAffilateChart.getAxisRight().setDrawGridLines(false);
        mAffilateChart.getAxisRight().setStartAtZero(false);
        mAffilateChart.setDoubleTapToZoomEnabled(true);
        //单指放缩
        mAffilateChart.setPinchZoom(false);


        mAffilateChart.setOnChartValueSelectedListener(this);
        mAffilateChart.setOnLoadingViewListener(this);

        if (mYAxisLablePostion != null) {
            mAffilateChart.getAxisLeft().setPosition(mYAxisLablePostion);
        }


    }

    public void syncAffilateChart() {
        setOffset();
        Matrix matrix = mKLineChart.getViewPortHandler().getMatrixTouch();
        float[] val = new float[9];
        matrix.getValues(val);

        mAffilateChart.syncMatrix(val[Matrix.MTRANS_X], val[Matrix.MSCALE_X], false);
        mAffilateChart.notifyDataSetChanged();
        mAffilateChart.invalidate();


    }

    public void syncKlineChart() {
        setOffset();
        Matrix matrix = mAffilateChart.getViewPortHandler().getMatrixTouch();
        float[] val = new float[9];
        matrix.getValues(val);

        mKLineChart.syncMatrix(val[Matrix.MTRANS_X], val[Matrix.MSCALE_X], false);
//        mAffilateChart.invalidate();
        mKLineChart.notifyDataSetChanged();

        mKLineChart.invalidate();
    }

    @Override
    public void onScrollDataSelect(Entry e, int dataSetIndex, Highlight h) {

        refreshAffilate();


//        if (mOnMarketSelectValueListener != null) {
//            mOnMarketSelectValueListener.onValueSelected(h.getXIndex(), e, null);
//        }

    }

    /*高亮联动*/
    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
//        QuoteStockInfoActivity.canRefresh = false;
//        Log.e("touch", "onValueSelected");
        tvKlineIndex.setVisibility(GONE);//高亮时右上角隐藏
        maxVolumeTextView.setVisibility(GONE);
//        mKLineChart.setValueMarkerViewPosition(h.getValuePosition());
//        mAffilateChart.setValueMarkerViewPosition(h.getValuePosition());
        mKLineChart.setHighValueMarkerViewVisibility(false);

        Entry entry = mKLineChart.highlightTouchWithoutEvent(new Highlight(e.getXIndex(), 0), 1);
        Entry affilateEntry = mAffilateChart.highlightTouchWithoutEvent(new Highlight(e.getXIndex(), 0), 1);
        if (mOnMarketSelectValueListener != null) {
            mOnMarketSelectValueListener.onValueSelected(e.getXIndex(), entry, affilateEntry);
        }


    }

    @Override
    public void onNothingSelected() {
//        QuoteStockInfoActivity.canRefresh = true;
//        Log.e("touch", "onNothingSelected");
        mKLineChart.highlightTouchWithoutEvent(null, 0);
        mAffilateChart.highlightTouchWithoutEvent(null, 0);
        tvKlineIndex.setVisibility(VISIBLE);
        maxVolumeTextView.setVisibility(VISIBLE);
        if (mOnMarketSelectValueListener != null) {
            mOnMarketSelectValueListener.onValueNothing();
        }

    }


    public ViewPortHandler getViewPortHandler() {
        return mKLineChart.getViewPortHandler();
    }

    @Override
    public void onLoadingViewStateOpen(Chart chart) {

        if (mOnLoadingviewListener != null) {
            mOnLoadingviewListener.onLoadingViewStateOpen(mKLineChart);
        }

        if (chart == mKLineChart) {
            mKLineChart.setLoadingViewOpen(true);
        } else {
            mKLineChart.setLoadingViewOpen(true);
        }
    }

    @Override
    public void onLoadingViewStateClose(Chart chart) {
        if (mOnLoadingviewListener != null) {
            mOnLoadingviewListener.onLoadingViewStateClose(mKLineChart);
        }
        if (chart == mKLineChart) {
            mAffilateChart.setLoadingViewOpen(false);
        } else {
            mKLineChart.setLoadingViewOpen(false);
        }
    }


    public void closeLoadingView() {
        mKLineChart.closeLoadingView();
        mAffilateChart.closeLoadingView();
    }

    public void setOnMarketSelectValueListener(OnMarketSelectValueListener l) {
        this.mOnMarketSelectValueListener = l;
    }

    public OnMarketSelectValueListener getOnMarketSelectValueListener() {
        return mOnMarketSelectValueListener;
    }

    /*设置图表右上方指标切换*/
    public void setChartIndexStr(String type) {
        String tv;
        if (type.equals(IndexModel.BOLLJUST)) {
            tv = type + "(" + hqKlineDb.getBOLL1() + "," + hqKlineDb.getBOLL2() + ")";
        } else {
            tv = type + "(" + hqKlineDb.getMA1() + "," + hqKlineDb.getMA2() + "," + hqKlineDb.getMA3() + ")";
        }

        if (isFullScreen) {
            tvKlineIndex.setClickable(false);
            tvKlineIndex.setText(tv);
        } else {
            tvKlineIndex.setClickable(true);
            tvKlineIndex.setText(tv + "⇋");
        }
    }

    /*下图表指标文字设置*/
    public void setBottomChartIndexStr(String type) {
        String tv = "";
        switch (type) {
            case IndexModel.IX_MACD:
                tv = "(" + hqKlineDb.getMACD1() + "," + hqKlineDb.getMACD2() + "," + hqKlineDb.getMACD3() + ")";
                break;
            case IndexModel.IX_KDJ:
                tv = "(" + hqKlineDb.getK() + "," + hqKlineDb.getD() + "," + hqKlineDb.getJ() + ")";
                break;
            case IndexModel.IX_RSI:
                tv = "(" + hqKlineDb.getRSI1() + "," + hqKlineDb.getRSI2() + "," + hqKlineDb.getRSI3() + ")";
                break;
            case IndexModel.IX_ADX:
                tv = "(9)";
                break;
            case IndexModel.IX_ATR:
                tv = "(15)";
                break;
        }
//        if (isFullScreen) {
//            tvAffilcateIndex.setClickable(false);
//            tvAffilcateIndex.setText(hqKlineDb.getBottomIndex() + tv);
//        } else {
//            tvAffilcateIndex.setClickable(true);
//            tvAffilcateIndex.setText(hqKlineDb.getBottomIndex() + tv + "▼");
//        }

    }

    public void setVolume(String maxVolume) {
        if (maxVolumeTextView != null) {
            maxVolumeTextView.setText(maxVolume);
        }
    }

    /*设置三条线和蜡烛图，可进行增删改*/
    public void setData(ArrayList<KLineData> yValues, int moveToLastType, String lineType) {
        if (yValues == null) {
            return;
        }
        kLinaCount = yValues.size();
        if (kLinaCount == 0) {
            return;
        }

        isMoveToLastType = moveToLastType;

        xVals = Arrays.asList(new String[kLinaCount]);
        yVals = new ArrayList<>();
        minList = new ArrayList<>();
        ma5List = new ArrayList<>();
        ma10List = new ArrayList<>();
        ma30List = new ArrayList<>();
        for (int i = 0; i < kLinaCount; i++) {
            KLineData d = yValues.get(i);
            float high = d.high;
            float low = d.low;
            float open = d.open;
            float close = d.close;
            yVals.add(new CandleEntry(i, high, low, open, close, d));
            minList.add(new Entry(d.close, i));
            ma5List.add(new Entry(d.ma5, i));
            ma10List.add(new Entry(d.ma10, i));
            ma30List.add(new Entry(d.ma30, i));
          /*  if (d.paiyuan != null) {
                paiList.add(new Entry(Float.NaN, i));
            }*/
        }

        candleDataSet = new CandleDataSet(yVals, "MinutesData Set");

        if (lineType.equals(CommonType.TIME_TYPE_MIN)) {
            candleDataSet.setHighlightEnabled(true);
            candleDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
//        set1.setColor(Color.rgb(80, 80, 80));
            candleDataSet.setHighLightColor(highlightColor);
            candleDataSet.setShadowWidth(1.0f);
            candleDataSet.setDecreasingColor(Color.TRANSPARENT);
            candleDataSet.setDecreasingPaintStyle(this.decreasingPaintStyle);
            candleDataSet.setIncreasingColor(Color.TRANSPARENT);
            candleDataSet.setIncreasingPaintStyle(this.increasingPaintStyle);
            candleDataSet.setDrawValues(false);
        }else {
            candleDataSet.setHighlightEnabled(true);
            candleDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
//        set1.setColor(Color.rgb(80, 80, 80));
            candleDataSet.setHighLightColor(highlightColor);
            candleDataSet.setShadowWidth(1.0f);
            candleDataSet.setDecreasingColor(this.decreasingColor);
            candleDataSet.setDecreasingPaintStyle(this.decreasingPaintStyle);
            candleDataSet.setIncreasingColor(this.increasingColor);
            candleDataSet.setIncreasingPaintStyle(this.increasingPaintStyle);
            candleDataSet.setDrawValues(false);
        }


/*
        ScatterDataSet scatterDataSet = new ScatterDataSet(paiList, "");
        scatterDataSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
        scatterDataSet.setColor(this.pointColor);
        scatterDataSet.setDrawValues(false);
        scatterDataSet.setScatterShapeSize(this.pointSize);*/
        candleData = new CandleData(xVals, candleDataSet);
        candleData.setHighlightEnabled(true);

        lineDataSets = new ArrayList<>();
        lineDataSetMin = new LineDataSet(minList, "min");
        lineDataSetMa5 = new LineDataSet(ma5List, "MA5");
        lineDataSetMa10 = new LineDataSet(ma10List, "MA10");
        lineDataSetMa30 = new LineDataSet(ma30List, "MA30");

        setLineDateSetStyle(lineDataSetMin);
        setLineDateSetStyle(lineDataSetMa5);
        setLineDateSetStyle(lineDataSetMa10);
        setLineDateSetStyle(lineDataSetMa30);



        if (lineType.equals(CommonType.TIME_TYPE_MIN)) {
            lineDataSetMin.setColor(this.highlightColor);
            lineDataSetMa5.setColor(this.ma5Color);
            lineDataSetMa10.setColor(this.ma10Color);
            lineDataSetMa30.setColor(this.ma60Color);
            lineDataSetMin.setFillAlpha(65);
            lineDataSetMin.setLineWidth(0.6f);
            lineDataSetMin.setDrawFilled(true);
            lineDataSetMin.setFillColor(Color.argb(225, 110, 109, 115));//灰色
            lineDataSetMin.setCircleColor(Color.argb(225, 110, 109, 115));//灰色
            lineDataSets.add(lineDataSetMin);
            lineDataSets.add(lineDataSetMa30);
        } else {
            lineDataSetMin.setColor(this.highlightColor);
            lineDataSetMa5.setColor(this.ma5Color);
            lineDataSetMa10.setColor(this.ma10Color);
            lineDataSetMa30.setColor(this.ma30Color);
            lineDataSets.add(lineDataSetMin);
            lineDataSets.add(lineDataSetMa5);
            lineDataSets.add(lineDataSetMa10);
            lineDataSets.add(lineDataSetMa30);
        }

        lineDate = new LineData(xVals, lineDataSets);
        lineDate.setHighlightEnabled(false);

        AJData combinedData = new AJData(xVals);
        combinedData.setData(candleData);
        combinedData.setData(lineDate);

        mKLineChart.setData(combinedData);
        //mKLineChart.setVisibleXRangeMinimum(5);
        /*mKLineChart.setVisibleXRangeMinimum(15);
        mKLineChart.setVisibleXRangeMaximum(150);
        mAffilateChart.setVisibleXRangeMinimum(15);
        mAffilateChart.setVisibleXRangeMaximum(150);*/
        //设置初始缩放
//        setInitScale(xVals);
        mKLineChart.setVisibleXRangeMaximum(90);
        mAffilateChart.setVisibleXRangeMaximum(90);
        mKLineChart.setVisibleXRangeMinimum(90);
        mAffilateChart.setVisibleXRangeMinimum(90);
        /*if(count>30) {
            final ViewPortHandler handler = mKLineChart.getViewPortHandler();
            Matrix touchmatrix = handler.getMatrixTouch();
            final float xscale = 2f;
            touchmatrix.postScale(xscale, 1f);
        }*/
        if (moveToLastType == 0) {
            moveToLast();
        } else {
            moveToFocus(90 * 2);
        }
//        moveToFocus(kLinaCount);
        mKLineChart.invalidate();
    }

    /*设置三条线和蜡烛图，可进行增删改*/
    public void setBollData(List<KLineData> yValues, int moveToLastType,String lineType) {
        if (yValues == null) {
            return;
        }
        int count = yValues.size();
        if (count == 0) {
            return;
        }

        isMoveToLastType = moveToLastType;

        List<String> xVals = Arrays.asList(new String[count]);
        ArrayList<CandleEntry> yVals = new ArrayList<>();
        ArrayList<Entry> minBollList = new ArrayList<>();
        ArrayList<Entry> upList = new ArrayList<>();
        ArrayList<Entry> midList = new ArrayList<>();
        ArrayList<Entry> lowList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            KLineData d = yValues.get(i);
            float high = d.high;
            float low = d.low;
            float open = d.open;
            float close = d.close;
            yVals.add(new CandleEntry(i, high, low, open, close, d));
            minBollList.add(new Entry(d.close, i));
            upList.add(new Entry(d.maUp, i));
            midList.add(new Entry(d.maMid, i));
            lowList.add(new Entry(d.maLow, i));

        }
        CandleDataSet set1 = new CandleDataSet(yVals, "MinutesData Set");
        LineDataSet min = new LineDataSet(minBollList, "min");
        LineDataSet up = new LineDataSet(upList, "up");
        LineDataSet mid = new LineDataSet(midList, "mid");
        LineDataSet low = new LineDataSet(lowList, "low");

        if (lineType.equals(CommonType.TIME_TYPE_MIN)) {
            min.setHighlightEnabled(true);
            min.setAxisDependency(YAxis.AxisDependency.LEFT);
            min.setHighLightColor(highlightColor);

            min.setFillAlpha(65);
            min.setLineWidth(0.6f);
            min.setDrawFilled(true);
            min.setFillColor(Color.argb(225, 110, 109, 115));//灰色
            min.setCircleColor(Color.argb(225, 110, 109, 115));//灰色

            set1.setShadowWidth(1.0f);
            set1.setDecreasingColor(Color.TRANSPARENT);
            set1.setDecreasingPaintStyle(this.decreasingPaintStyle);
            set1.setIncreasingColor(Color.TRANSPARENT);
            set1.setIncreasingPaintStyle(this.increasingPaintStyle);
            set1.setDrawValues(false);
        }else {
            set1.setHighlightEnabled(true);
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//        set1.setColor(Color.rgb(80, 80, 80));
            set1.setHighLightColor(highlightColor);
            set1.setShadowWidth(1.0f);
            set1.setDecreasingColor(this.decreasingColor);
            set1.setDecreasingPaintStyle(this.decreasingPaintStyle);
            set1.setIncreasingColor(this.increasingColor);
            set1.setIncreasingPaintStyle(this.increasingPaintStyle);
            set1.setDrawValues(false);
        }

        CandleData data = new CandleData(xVals, set1);
        data.setHighlightEnabled(true);
        ArrayList<LineDataSet> lineDataSets = new ArrayList<>();

        setLineDateSetStyle(min);
        setLineDateSetStyle(up);
        setLineDateSetStyle(mid);
        setLineDateSetStyle(low);

        min.setColor(this.highlightColor);
        up.setColor(this.ma5Color);
        mid.setColor(this.ma10Color);
        low.setColor(this.ma30Color);

        lineDataSets.add(min);
        lineDataSets.add(up);
        lineDataSets.add(mid);
        lineDataSets.add(low);

        LineData lineDate = new LineData(xVals, lineDataSets);
        lineDate.setHighlightEnabled(false);

        AJData combinedData = new AJData(xVals);
        combinedData.setData(data);
        combinedData.setData(lineDate);

        mKLineChart.setData(combinedData);
      /*  mKLineChart.setVisibleXRangeMinimum(15);
        mKLineChart.setVisibleXRangeMaximum(150);
        mAffilateChart.setVisibleXRangeMinimum(15);
        mAffilateChart.setVisibleXRangeMaximum(150);*/
        //mKLineChart.setVisibleXRangeMinimum(5);
      /*  mKLineChart.setVisibleXRangeMinimum(10);
        mAffilateChart.setVisibleXRangeMinimum(10);*/
        //设置初始缩放
        setInitScale(xVals);

        if (moveToLastType == 0) {
            moveToLast();
        } else {
//            moveToFocus(count);
        }
//        moveToFocus(count);
       /* if(count>30) {
            final ViewPortHandler handler = mKLineChart.getViewPortHandler();
            Matrix touchmatrix = handler.getMatrixTouch();
            final float xscale = 2f;
            touchmatrix.postScale(xscale, 1f);
        }*/
        mKLineChart.invalidate();
    }

    /*设置三条线和蜡烛图，可进行增删改*/
    public void addChartData(ArrayList<KLineData> lineDataArrayList, int moveToLastType) {
        if (lineDataArrayList == null) {
            return;
        }
        int linaCount = lineDataArrayList.size() + kLinaCount;
        if (linaCount == 0) {
            return;
        }

        isMoveToLastType = moveToLastType;

        List<String> xVals1 = Arrays.asList(new String[linaCount]);

//        xVals = Arrays.asList(new String[kLinaCount]);

        ArrayList<CandleEntry> yValue1 = new ArrayList<>();
//        yVals = new ArrayList<>();
//        ma5List = new ArrayList<>();
//        ma10List = new ArrayList<>();
//        ma30List = new ArrayList<>();
        for (int i = 0; i < kLinaCount; i++) {
            KLineData d = lineDataArrayList.get(i);
            float high = d.high;
            float low = d.low;
            float open = d.open;
            float close = d.close;
            yValue1.add(new CandleEntry(i, high, low, open, close, d));
            ma5List.add(0, new Entry(d.ma5, i));
            ma10List.add(0, new Entry(d.ma10, i));
            ma30List.add(0, new Entry(d.ma30, i));
          /*  if (d.paiyuan != null) {
                paiList.add(new Entry(Float.NaN, i));
            }*/
        }

        CandleDataSet candleDataSet1 = new CandleDataSet(yValue1, "MinutesData Set");
        candleDataSet1.setHighlightEnabled(true);
        candleDataSet1.setAxisDependency(YAxis.AxisDependency.LEFT);
        candleDataSet1.setHighLightColor(highlightColor);
        candleDataSet1.setShadowWidth(1.0f);
        candleDataSet1.setDecreasingColor(this.decreasingColor);
        candleDataSet1.setDecreasingPaintStyle(this.decreasingPaintStyle);
        candleDataSet1.setIncreasingColor(this.increasingColor);
        candleDataSet1.setIncreasingPaintStyle(this.increasingPaintStyle);
        candleDataSet1.setDrawValues(false);

//        CandleData candleData1 = new CandleData(xVals1, candleDataSet1);
//        candleData1.addEntry();
//        candleData1.setHighlightEnabled(true);

        for (int i = 0; i < kLinaCount; i++) {
            candleData.addEntry(yValue1.get(i), i);
        }

//        lineDataSets = new ArrayList<>();
//        lineDataSetMa5 = new LineDataSet(ma5List, "MA5");
//        lineDataSetMa10 = new LineDataSet(ma10List, "MA10");
//        lineDataSetMa30 = new LineDataSet(ma30List, "MA30");
//
//        setLineDateSetStyle(lineDataSetMa5);//设置属性
//        setLineDateSetStyle(lineDataSetMa10);
//        setLineDateSetStyle(lineDataSetMa30);
//
//        lineDataSetMa5.setColor(this.ma5Color);
//        lineDataSetMa10.setColor(this.ma10Color);
//        lineDataSetMa30.setColor(this.ma30Color);
//
//        lineDataSets.add(lineDataSetMa5);
//        lineDataSets.add(lineDataSetMa10);
//        lineDataSets.add(lineDataSetMa30);

//        lineDate = new LineData(xVals, lineDataSets);
//        lineDate.setHighlightEnabled(false);

//        lineDate.clearValues();
//        lineDate.addDataSet(lineDataSets.get(0));
//        lineDate.addDataSet(lineDataSets.get(1));
//        lineDate.addDataSet(lineDataSets.get(2));
//        lineDate.setHighlightEnabled(false);

//        AJData combinedData = new AJData(xVals);
//        combinedData.setData(candleData);
//        combinedData.setData(lineDate);

//        mKLineChart.setData(combinedData);

//        lineDate.notifyDataChanged();
        candleData.notifyDataChanged();
        mKLineChart.notifyDataSetChanged();
        mKLineChart.postInvalidate();


        //mKLineChart.setVisibleXRangeMinimum(5);
        /*mKLineChart.setVisibleXRangeMinimum(15);
        mKLineChart.setVisibleXRangeMaximum(150);
        mAffilateChart.setVisibleXRangeMinimum(15);
        mAffilateChart.setVisibleXRangeMaximum(150);*/
        //设置初始缩放
//        setInitScale(xVals);
        mKLineChart.setVisibleXRangeMaximum(90);
        mAffilateChart.setVisibleXRangeMaximum(90);
        mKLineChart.setVisibleXRangeMinimum(90);
        mAffilateChart.setVisibleXRangeMinimum(90);
        /*if(count>30) {
            final ViewPortHandler handler = mKLineChart.getViewPortHandler();
            Matrix touchmatrix = handler.getMatrixTouch();
            final float xscale = 2f;
            touchmatrix.postScale(xscale, 1f);
        }*/
        if (moveToLastType == 0) {
            moveToLast();
        } else {
//            moveToFocus(kLinaCount);
        }
//        moveToFocus(kLinaCount);
        mKLineChart.invalidate();
    }

    /**
     * chart增加数据
     *
     * @param kLineData K线数据
     */
    public void displayChartForEntry(KLineData kLineData, int moveToLastType) {

        if (kLineData == null || kLinaCount <= 0) {
            return;
        }


        int index = kLinaCount - 1;
        float high = kLineData.high;
        float low = kLineData.low;
        float open = kLineData.open;
        float close = kLineData.close;

        if (lineDataSetMa5 != null && lineDataSetMa5.getEntryCount() != 0) {
            int indexMa5 = 0;
            lineDataSetMa5.removeEntry(indexMa5);
            lineDataSetMa5.addEntry(new Entry(kLineData.ma5, indexMa5));

        }
        if (lineDataSetMa10 != null && lineDataSetMa10.getEntryCount() != 0) {
            int indexMa10 = 0;
            lineDataSetMa10.removeEntry(indexMa10);
            lineDataSetMa10.addEntry(new Entry(kLineData.ma10, indexMa10));

        }
        if (lineDataSetMa30 != null && lineDataSetMa30.getEntryCount() != 0) {
            int indexMa30 = 0;
            lineDataSetMa30.removeEntry(indexMa30);
            lineDataSetMa30.addEntry(new Entry(kLineData.ma30, indexMa30));

        }

        lineDataSets.clear();
        lineDataSets.add(lineDataSetMa5);
        lineDataSets.add(lineDataSetMa10);
        lineDataSets.add(lineDataSetMa30);

        if (xVals != null && xVals.size() != 0) {
            xVals.remove(xVals.size() - 1);
            String time = kLineData.date;
            xVals.add(time + "");
        }

        if (lineDate != null) {
            lineDate.notifyDataChanged();
        }

        //修改candle
        if (candleDataSet != null) {
            int candleEntryCount = candleDataSet.getEntryCount();
            candleDataSet.removeEntry(candleEntryCount - 1);
            candleDataSet.addEntry(new CandleEntry(index, high, low, open, close, kLineData));
            candleDataSet.notifyDataSetChanged();
            mKLineChart.notifyDataSetChanged();
            mKLineChart.postInvalidate();

        }


    }


    public void clearChart() {
        mKLineChart.clear();
        mAffilateChart.clear();
        mKLineChart.invalidate();
        mAffilateChart.invalidate();
    }

    public void setInitScale(List<String> xVals) {
        //设置初始缩放
        final ViewPortHandler handler = mKLineChart.getViewPortHandler();
        Matrix touchmatrix = handler.getMatrixTouch();
        final float xscale = culcScale(xVals.size()) / culcMinscale(xVals.size());
        touchmatrix.setScale(1f, 1f);
        touchmatrix.postScale(xscale, 1f);

    }

    float culcScale(float count) {
        float min = 1;
        /** 90这个值决定一屏显示多少个数据*/
        min = count / 90 * 4;
        if (min < 1)
            min = 1;
        return min;
    }

    //计算最大缩放比例
    float culcMaxscale(float count) {
        float max = 1;
        max = count / 90 * 5;
        return max;
    }

    //计算最小缩放比例
    float culcMinscale(float count) {
        float min = 1;
        min = count / 90 * 4;
        if (min < 1)
            min = 1;
        return min;
    }

    private void setLineDateSetStyle(LineDataSet dataSet) {
        dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        dataSet.setDrawCircles(false);
        dataSet.setDrawValues(false);
        dataSet.setLineWidth(1f);
        dataSet.setHighlightEnabled(false);
    }

    public void setShowXLabels(SparseArray<String> labels) {

        SparseArray<String> l = labels.clone();
        mKLineChartXAxis.setShowLabels(l);
        mAffilateChart.getXAxis().setShowLabels(l);
    }

    /*设置三条线颜色*/
    public void setMAColor(int ma5Color, int ma10Color, int ma30Color) {
        this.ma5Color = ma5Color;
        this.ma10Color = ma10Color;
        this.ma30Color = ma30Color;
    }

    public void setHighlightColor(int color) {
        this.highlightColor = color;
    }

    //
    public void setDecreasingColor(int color) {
        this.decreasingColor = color;
    }

    public void setDecreasingPaintStyle(Paint.Style style) {
        this.decreasingPaintStyle = style;
    }

    public void setIncreasingColor(int color) {
        this.increasingColor = color;
    }

    public void setIncreasingPaintStyle(Paint.Style style) {
        this.increasingPaintStyle = style;
    }

    public void setPointColor(int color) {
        this.pointColor = color;
    }

    public void setPointSize(float size) {
        this.pointSize = size;
    }

    public void setOnLoadingViewListener(AJChartTouchListener.OnLoadingViewListener l) {

        this.mOnLoadingviewListener = l;
    }

    public void setYAxixPosition(YAxis.YAxisLabelPosition pos) {
        mYAxisLablePostion = pos;
        mKLineChart.getAxisLeft().setPosition(pos);
    }


    public void moveToLast() {
        try {
            AJData lineData = mKLineChart.getData();
            if (lineData != null && lineData.getXValCount() > 0) {
                int xValCount = lineData.getXValCount();
                mAffilateChart.moveViewToX(xValCount - 1);
                mKLineChart.moveViewToX(xValCount - 1);
                mKLineChart.notifyDataSetChanged();
                mAffilateChart.notifyDataSetChanged();
                invalidate();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void moveToFocus(int focus) {
        mAffilateChart.moveViewToX(focus - 1);
        mKLineChart.moveViewToX(focus - 1);
        Log.e("quote", "moveToFocus==" + focus);
        mKLineChart.notifyDataSetChanged();
        mAffilateChart.notifyDataSetChanged();
        invalidate();

    }


    public KLineChart getmKLineChart() {
        return this.mKLineChart;
    }

    public KLineChart getAffilateChart() {
        return this.mAffilateChart;
    }

    /*x轴显示范围，没范围，则默认一界面显示所有，差评*/
    public void setVisibleXRange(float minRang, float maxRang) {
        this.minRang = minRang;
        this.maxRang = maxRang;
        mKLineChart.setVisibleXRange(minRang, maxRang);
        mAffilateChart.setVisibleXRange(minRang, maxRang);

    }

    protected void culcXoffset(final ViewPortHandler handler) {
        ViewTreeObserver vto = mKLineChart.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mKLineChart.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                float offset = (handler.contentRight() - handler.contentLeft()) * (culcScale(mKLineChart.getXValCount()) - 1);
                Matrix touchmatrix = handler.getMatrixTouch();
                touchmatrix.postTranslate(-offset, 0);
            }
        });
    }

    @Override
    public void invalidate() {
        super.invalidate();
        mKLineChart.invalidate();
        mAffilateChart.invalidate();
    }

    /*暂时为了解决ma boll线切换bug*/
    public void stopChart() {
        mKLineChart.setDragDecelerationEnabled(false);
        mAffilateChart.setDragDecelerationEnabled(false);
    }

    public void clearKLineData() {
        mKLineChart.clear();
    }

    public void clearAffilateData() {
        mAffilateChart.clear();
    }

    public void setLRMarkerView(MarkerView quoteInfoView, MarkerView leftView, MarkerView rightView, MarkerView xaxisView, boolean isFullScreen) {
//        if (!isFullScreen) {
        mKLineChart.setQuoteInfoMarkerView(quoteInfoView);
//        }
        mKLineChart.setLeftMarkerView(leftView);
        mKLineChart.setRightMarkerView(rightView);
        mKLineChart.setXAxisMarkerView(xaxisView);
    }

    public void setLMarkerView(MarkerView leftView) {
        mKLineChart.setLeftMarkerView(leftView);
    }

    public void setValueMarkerView(ValueMarkerView markerView, boolean isFullScreen) {
//        if (isFullScreen) {
        mKLineChart.setValueMarkerView(markerView);
//        }
    }

    public void setHighLightCircle(HightCircleMarkerView highLightCircle) {
        mKLineChart.setHighLightCircleView(highLightCircle);
    }

    public void restoreScale() {
        mKLineChart.restoreScale();
        mAffilateChart.restoreScale();
    }

    public void setYValueFormatter(ValueFormatter f) {
        mKLineChart.getAxisLeft().setValueFormatter(f);
    }

    public void setXAxisLabelPosition(int position) {

        float offset = 10;
        mXLabelPosition = position;
        if (position == AJXAxis.XAXISPOSITION_MIDDLE) {
            mKLineChartXAxis.setDrawLabels(true);
            mAffilateChart.getXAxis().setDrawLabels(false);
        } else if (position == AJXAxis.XAXISPOSITION_BOTTOM) {
            mKLineChartXAxis.setDrawLabels(false);
            mAffilateChart.getXAxis().setDrawLabels(true);
        }

     /*   mKLineChart.setExtraOffsets(offset, offset, offset, 0);
        mAffilateChart.setExtraOffsets(offset, offset, offset, offset);*/


    }

    public void setYAxisLabelCount(int count) {
        mKLineChart.getAxisLeft().setLabelCount(count);
    }

    public void setShowOnlyMinMax(boolean enabled) {
        mKLineChart.getAxisLeft().setShowOnlyMinMax(enabled);
    }

    public void setOnChartGestureListener(OnChartGestureListener l) {
        mKLineChart.requestDisallowInterceptTouchEvent(true);
        mKLineChart.setOnChartGestureListener(l);
    }

    public void setYAxisOffset(float offset) {
        this.mYLabelOffset = offset;
        mKLineChart.getAxisLeft().setXOffset(mYLabelOffset);
        mAffilateChart.getAxisLeft().setXOffset(mYLabelOffset);
    }

    public void setVisiableMin(float minRang) {
        mKLineChart.setVisibleXRangeMinimum(minRang);
        mAffilateChart.setVisibleXRangeMinimum(minRang);
    }

    public int getVisiableMax() {
        return mKLineChart.getHighestVisibleXIndex();
    }

    /**
     * 为了避免yright没有label,有highlight,左右两边取一样offset
     */
    private void setOffset() {

        float offsetLeft = 0;
        float offsetRight = 0;


        float lMax1 = this.leftOffset;
        if (mKLineChart.getAxisLeft().needsOffset()) {
            lMax1 = mKLineChart.getAxisLeft().getRequiredWidthSpace(mKLineChart.getRendererLeftYAxis().getPaintAxisLabels());
        }

        float lMax2 = 0;
        if (mAffilateChart.getAxisLeft().needsOffset()) {
            lMax2 = mAffilateChart.getAxisLeft().getRequiredWidthSpace(mAffilateChart.getRendererLeftYAxis().getPaintAxisLabels());
        }

        float rMax = this.rightOffset;
        if (mKLineChart.getAxisRight().needsOffset()) {
            rMax = mKLineChart.getAxisRight().getRequiredWidthSpace(mKLineChart.getRendererRightYAxis().getPaintAxisLabels());
        }

        if (lMax1 < lMax2) {
            lMax1 = lMax2;
        }


        offsetLeft = Utils.convertPixelsToDp(lMax1);
        offsetRight = Utils.convertPixelsToDp(rMax);
    /*    if (offsetLeft > offsetRight)
            offsetRight = offsetLeft;*/

        mAffilateChart.setExtraLeftOffset(offsetLeft);
        mAffilateChart.setExtraRightOffset(offsetRight);
        mKLineChart.setExtraLeftOffset(offsetLeft);
        mKLineChart.setExtraRightOffset(offsetRight);

        mKLineChart.setExtraTopOffset(2);//距离tab
        mAffilateChart.setExtraTopOffset(0);//距离

    }

    public void setNoDataText(String txt) {
        mKLineChart.setNoDataText(txt);
    }

    public void setAffilateChartNoDataText(String txt) {
        mAffilateChart.setNoDataText(txt);
    }

    public void refreshAffilate() {
//        QuoteStockInfoActivity.canRefresh = false;
        if (mAffilateChart != null && mAffilateChart.getData() != null) {
            float max = mAffilateChart.getYMax();

            if (mOnRefreshAffilcateChart != null) {
                mOnRefreshAffilcateChart.onChangeLeftAxis(max);
            }
        }
    }

    public void setOnRefreshAffilcateChart(OnRefreshAffilcateChart l) {
        this.mOnRefreshAffilcateChart = l;
    }

    public void setXMarkerView(MarkerView markerView) {
        mKLineChart.setXAxisMarkerView(markerView);
    }

    public void setDrawYLabels(boolean enable) {
        mKLineChart.getAxisLeft().setDrawLabels(enable);
        mAffilateChart.getAxisLeft().setDrawLabels(enable);
        mIsHiddenYLabels = enable;

    }

    public void setDrawXLabels(boolean enable) {


        if (mXLabelPosition == AJXAxis.XAXISPOSITION_MIDDLE) {
            mKLineChart.getXAxis().setDrawLabels(enable);
        } else if (mXLabelPosition == AJXAxis.XAXISPOSITION_BOTTOM) {
            mAffilateChart.getXAxis().setDrawLabels(enable);
        }


    }

    public void setGridLineColor(int color) {
        mKLineChart.getAxisLeft().setGridColor(color);
        mKLineChart.getXAxis().setGridColor(color);
        mKLineChart.getAxisLeft().setAxisLineColor(color);
        mKLineChart.getXAxis().setAxisLineColor(color);
        this.gridLineColor = color;
    }

    public void setXAxisLabelColor(int color) {

        if (mXLabelPosition == AJXAxis.XAXISPOSITION_MIDDLE) {
            mKLineChart.getXAxis().setTextColor(color);
        } else if (mXLabelPosition == AJXAxis.XAXISPOSITION_BOTTOM) {
            mAffilateChart.getXAxis().setTextColor(color);
        }


    }

    public void setYAxixLabelColor(int color) {
        mKLineChart.getAxisLeft().setTextColor(color);
        this.yAxixLabelColor = color;
    }

    public interface OnRefreshAffilcateChart {
        void onChangeLeftAxis(float max);
    }
}
